<?php
include ("httpHelper.php");
$action=$_GET['action'];
if($action=='add'){
    $stockCode=$_GET['stockCode'];
    
    addStockCode($stockCode);
    
}else if($action=='getCode'){
   echo getSqlStockCode();
}else if($action=='updateStock'){
    $stockCode=$_GET['stockCode'];
    //echo curl_request("./get.php?f=USD&t=CNY");
    updateStock($stockCode);
}

function updateStock($code){
    $url = "https://gupiao.baidu.com/api/rails/stockbasicbatch";  
    $data ="from=pc&os_ver=1&cuid=xxx&vv=100&format=json&stock_code=".$code."&timestamp=".intval(time());
     $result = vpost($url,$data);   
      $result =json_decode($result); 
    $exchange=$result->data[0]->exchange;
    
     $capitalization=$result->data[0]->capitalization;
    
    if($exchange=='sh'||$exchange=='sz'){
        $dlv=1/curl_request("./get.php?f=USD&t=CNY");
         //echo $stockValue=round($capitalization*($dlv)/100000000,3);
    }else if($exchange=='hk'){
      $dlv=1/curl_request("./get.php?f=USD&t=HKD");  
        // echo $stockValue=round($capitalization*($dlv)/100000000,3);
    }else if($exchange=='us'){
       $dlv=1; 
        // echo $stockValue=round($capitalization*($dlv)/100000000,3);
    }
    echo $stockValue=round($capitalization*($dlv)/100000000,2);
    updateStockValue($code,$stockValue);
    
}
function updateStockValue($code,$value){
    $sql="UPDATE stockcode SET value='".$value."' WHERE code='".$code."'";
   // echo $sql;
    $conn=getConn();
    echo mysqli_query($conn,$sql);
     mysqli_close($conn);  
}

//添加stock code
function addStockCode($code){
    $sql="INSERT INTO stockcode(code, value) VALUES('".$code."','0')";
   // echo $sql;
    $conn=getConn();
    echo mysqli_query($conn,$sql);
     mysqli_close($conn);
}

function getSqlStockCode(){
    $codes="";
    $sql ="select code from stockCode where 1=1 order by value*1 desc "; //SQL语句

    $result = mysqli_query(getConn(),$sql); //查询
    //mysqli_close(); //关闭MySQL连接
      while($row = mysqli_fetch_array($result))

    {

    if($codes!=""){
        $codes= $codes.",".$row['code'] ;
    }else{
        $codes=$row['code'];
    }
    }  

    return $codes;
}

function getConn(){
    $mysql_server_name='localhost'; //改成自己的mysql数据库服务器
 
    $mysql_username='root'; //改成自己的mysql数据库用户名

    $mysql_password='drc123'; //改成自己的mysql数据库密码

    $mysql_database='test'; //改成自己的mysql数据库名
    $conn=mysqli_connect($mysql_server_name,$mysql_username,$mysql_password,$mysql_database); //连接数据库
 return $conn;
}


?>